<?php

namespace App\Http\Controllers\V1;

use Throwable;
use App\Support\Code;
use App\Models\Packet;
use App\Support\Currency;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Resources\PacketCollection;

class PacketController extends ApiController
{
    public function index()
    {
        return $this->success(
            new PacketCollection(
                Packet::where('user_id', $this->getUser()->id)->orderByDesc('created_at')->paginate()
            )
        );
    }

    public function count()
    {
        $user = $this->getUser();
        $query = Packet::whereUserId($user->id)->select('id', 'value', 'currency')
            ->where('status', 0)->where('expired_at', '>', now());
        $data = [
            'day_vrts' => (clone $query)
                ->where('type', Packet::TYPE_DAY)
                ->where('currency', Currency::VRTS)->get()->each(function ($item) {
                    $item->value = number_format($item->value, 5);
                    $item->currency = Str::upper(Currency::getStrByCode($item->currency));
                }),
            'team_vrts' => (clone $query)
                ->where('type', Packet::TYPE_TEAM)
                ->where('currency', Currency::VRTS)->get()->each(function ($item) {
                    $item->value = number_format($item->value, 5);
                    $item->currency = Str::upper(Currency::getStrByCode($item->currency));
                }),
            'day_yec' => (clone $query)
                ->where('type', Packet::TYPE_DAY)
                ->where('currency', Currency::YEC)->get()->each(function ($item) {
                    $item->value = number_format($item->value, 5);
                    $item->currency = Str::upper(Currency::getStrByCode($item->currency));
                }),
        ];

        $data['day_yec_count'] = $data['day_yec']->count();
        $data['day_vrts_count'] = $data['day_vrts']->count();
        $data['team_vrts_count'] = $data['team_vrts']->count();

        return $this->success($data);
    }

    public function status()
    {
        $count = Packet::whereUserId($this->getUser()->id)
            ->where('status', 0)->where('expired_at', '>', now())->count();

        return $this->success(['count' => $count]);
    }

    public function update($id)
    {
        $user = $this->getUser();
        $packet = Packet::find($id);
        if ($packet->expired_at < now() && $packet->status == Packet::STATUS_UNCLAIMED) {
            $packet->update(['status' => Packet::STATUS_EXPIRED]);
            return $this->fail(Code::NOT_EXISTS, '红包已过期！');
        }
        $func = function () use ($packet, $user) {
            if ($packet->currency == Currency::VRTS) {
                $packet->before = $user->vrt;
                $packet->before_s = $user->vrts;
            } else {
                $packet->before = $user->yec;
                $packet->before_s = $user->yecs;
            }
            $packet->record()->create([
                'type' => '领取红包',
                'user_id' => $user->id,
                'value' => $packet->value,
                'currency' => $packet->currency
            ]);
            $packet->status = Packet::STATUS_CLAIMED;
            $packet->save();
        };
        try {
            DB::transaction($func);
            if ($packet->currency == Currency::VRTS) {
                $packet->after = $user->vrt;
                $packet->after_s = $user->vrts;
            } else {
                $packet->after = $user->yec;
                $packet->after_s = $user->yecs;
            }
            $packet->save();
        } catch (Throwable $exception) {
            Log::error('红包领取错误：' . $exception->getMessage());
            return $this->fail(Code::SERVER_ERROR, '红包领取出错！');
        }
        return $this->setMsg('红包领取成功')->success();
    }
}
